<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<link rel="stylesheet" type="text/css" href="css/reset.css">
	<link rel="stylesheet" type="text/css" href="css/style.css">
	<title></title>
</head>
<body>
	<ul id="warp">
		<li>一级第一个
			<ul>
				<li>二级第一个</li>
				<li>二级第二个</li>
				<li>二级第三个</li>
				<li>二级第四个
					<ul>
						<li>三级第一个</li>
						<li>三级第二个
							<ul>
								<li>四级1</li>
								<li>四级2</li>
								<li>四级3</li>
								<li>四级4</li>
								<li>四级5</li>
								<li>四级6</li>
								<li>四级7</li>
								<li>四级8</li>
							</ul>
						</li>
						<li>三级第三个</li>
					</ul>
				</li>
			</ul>
		</li>
		<li>一级第二个</li>
		<li>一级第三个</li>
		<li>一级第四个</li>
		<li>一级第五个
			<ul>
				<li>二级第五个</li>
				<li>二级第六个</li>
			</ul>
		</li>
		<li>一级第六个</li>
	</ul>
</body>
	<script type="text/javascript">
		var warp = document.getElementById('warp');
		var lis = warp.getElementsByTagName('li');
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;
		var timer;
		var leftBool = false;

		// 鼠标右键事件
		document.oncontextmenu = function(e){
			var ev = e || event;
			
			warp.style.display = 'block';
			if (ev.clientX > windowWidth - warp.offsetWidth) {
				warp.style.left = windowWidth - warp.offsetWidth + 'px';
			}else{
				warp.style.left = ev.clientX + 'px';
			}
			if (ev.clientY > windowHeight - warp.offsetHeight) {
				warp.style.top = windowHeight - warp.offsetHeight + 'px';
			}else{
				warp.style.top = ev.clientY + 'px';

			}

			return false;
		}

		// 点击空白处
		document.onclick = function(e){
			warp.style.display = 'none';
			leftBool = false;
		}

		// 阻止冒泡
		warp.onclick = function(e){
			var ev = e || event;
			ev.cancelBubble = true;
		}

		for (var i = 0; i < lis.length; i++) {
			lis[i].onmouseenter = function(){
				if (this.children.length > 0) {
					if (this.children[0].tagName == 'UL') {
						clearTimeout(this.timer);						
						this.children[0].style.display = 'block';
						var ulPostion = getPostion(warp);
						console.log('宽：' + this.children[0].offsetWidth);
						if (ulPostion.left + warp.offsetWidth *4 >= windowWidth) {
							this.children[0].style.left = '-98px';
						}else{
							this.children[0].style.left = '98px';
						}
					}
				}
			}

			lis[i].onmouseleave = function(){
				if (this.children.length > 0) {
					if (this.children[0].tagName == 'UL') {
						var li = this;
						timer = setTimeout(function(){
							li.children[0].style.display = 'none';
							li.children[0].style.left = '98px';
						},300);
						this.timer = timer;
					}
				}
			}
		}

		function getPostion(obj){
			var top = obj.offsetTop;
			var left = obj.offsetLeft;
			var parent = obj.offsetParent;

			while(parent){
				top += parent.offsetTop;
				left += parent.offsetLeft;
				parent = parent.offsetParent;
			}
			console.log({top:top,left:left});
			return {top:top,left:left};
		}









	</script>
</html>